package uts.sdk.modules.lnxZhiyiTools;

import android.content.Context;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDevice;
import android.util.Base64;
import android.util.Log;

import com.zkteco.android.IDReader.WLTService;
import com.zkteco.android.biometric.core.device.ParameterHelper;
import com.zkteco.android.biometric.core.device.TransportType;
import com.zkteco.android.biometric.core.utils.LogHelper;
import com.zkteco.android.biometric.module.idcard.IDCardReader;
import com.zkteco.android.biometric.module.idcard.IDCardReaderFactory;
import com.zkteco.android.biometric.module.idcard.IDCardType;
import com.zkteco.android.biometric.module.idcard.exception.IDCardReaderException;
import com.zkteco.android.biometric.module.idcard.meta.IDCardInfo;
import com.zkteco.android.biometric.module.idcard.meta.IDPRPCardInfo;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

import uts.sdk.modules.lnxZhiyiTools.ZKUSBManager.ZKUSBManager;
import uts.sdk.modules.lnxZhiyiTools.ZKUSBManager.ZKUSBManagerListener;


public class IDCardLocal {



    public static JSONObject idCardResult = new JSONObject();

    private static ZKUSBManager zkusbManager = null;
    private static IDCardReader idCardReader = null;
    private static final int VID = 1024;    //IDR VID
    private static final int PID = 50010;     //IDR PID
    private static Context contextActivity = null;
    private static CountDownLatch countDownLatch = null;
    private static boolean bStarted = false;
    private static boolean bCancel = false;
    private static boolean bRepeatRead = false;

    private static Object lock = new Object();

    private static boolean isLibraryLoaded = false;



    private static ZKUSBManagerListener zkusbManagerListener = new ZKUSBManagerListener() {
        @Override
        public void onCheckPermission(int result) {
            openDevice();
        }

        @Override
        public void onUSBArrived(UsbDevice device) {
            setResult(0,1,"发现阅读器接入",null);
        }

        @Override
        public void onUSBRemoved(UsbDevice device) {
            setResult(-1,-1,"阅读器USB被拔出",null);
        }
    };


    private static void setResult(Integer code,Integer resultCode,String message,String resultMessage){
        try {
            idCardResult.put("code",code);
            idCardResult.put("resultCode",resultCode);
            idCardResult.put("message",message);
            idCardResult.put("resultMessage",resultMessage);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }


    public static void initDevice(Context context) {
        contextActivity = context;
        // initSo(context);
        zkusbManager = new ZKUSBManager(context, zkusbManagerListener);
        zkusbManager.registerUSBPermissionReceiver();
        zkusbManager.initUSBPermission(VID,PID);
    }

    public static JSONObject getResult() {
        return idCardResult;
    }


    public static JSONObject clearResult() {
        idCardResult = new JSONObject();
        return idCardResult;
    }

    public static Context getAppContextSafely() {
        return contextActivity;
    }

    public static String decodeImg(byte[] photo){
        // if(photo != null){
        Bitmap bmpPhoto = null;
        byte[] buf = new byte[3 * 102 * 126];
        int photoResult = WLTService.wlt2Bmp(photo,buf);
        if (1 == photoResult) {
            bmpPhoto = Bgr2Bitmap(buf);
        }
        if(bmpPhoto == null){
            return "";
        }
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //把bitmap100%高质量压缩 到 output对象里
        bmpPhoto.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
        byte[] byteArray = outputStream.toByteArray();
        String imgStr = Base64.encodeToString(
                byteArray,
                Base64.DEFAULT
        );
        return imgStr;
        // }
        // 	console.log("照片:空")
        // return ""
    }


    private static void startIDCardReader() {
        if (null != idCardReader)
        {
            IDCardReaderFactory.destroy(idCardReader);
            idCardReader = null;
        }
        // Define output log level
        LogHelper.setLevel(Log.VERBOSE);
        // Start fingerprint sensor
        Map idrparams = new HashMap();
        idrparams.put(ParameterHelper.PARAM_KEY_VID, VID);
        idrparams.put(ParameterHelper.PARAM_KEY_PID, PID);
        idCardReader = IDCardReaderFactory.createIDCardReader(contextActivity, TransportType.USB, idrparams);
    }



    private static void openDevice()
    {
        startIDCardReader();
        try {
            idCardReader.open(0);
            countDownLatch = new CountDownLatch(1);
            new Thread(new Runnable() {
                public void run() {
                    bCancel = false;
                    while (!bCancel) {

                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        boolean ret = false;
                        final long nTickstart = System.currentTimeMillis();
                        try {
                            idCardReader.findCard(0);
                            idCardReader.selectCard(0);
                        }catch (IDCardReaderException e)
                        {
                            if (!bRepeatRead)
                            {
                                continue;
                            }
                        }
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        int cardType = 0;
                        setResult(2,2,null,"正在读卡，请勿移动身份证!" );
                        try {
                            cardType = idCardReader.readCardEx(0, 0);
                        }
                        catch (IDCardReaderException e)
                        {
                            setResult(2,5,null,"读卡失败，错误信息：" + e.getMessage());
                            continue;
                        }
                        if (cardType == IDCardType.TYPE_CARD_SFZ || cardType == IDCardType.TYPE_CARD_PRP || cardType == IDCardType.TYPE_CARD_GAT)
                        {
                            final long nTickCommuUsed = (System.currentTimeMillis()-nTickstart);
//                            updateUIByCardType(cardType);
                            if (cardType == IDCardType.TYPE_CARD_SFZ || cardType == IDCardType.TYPE_CARD_GAT)
                            {
                                IDCardInfo idCardInfo = idCardReader.getLastIDCardInfo();
                                final String name = idCardInfo.getName();
                                final String sex = idCardInfo.getSex();
                                final String nation = idCardInfo.getNation();
                                final String born = idCardInfo.getBirth();
                                final String licid = idCardInfo.getId();
                                final String depart = idCardInfo.getDepart();
                                final String expireDate = idCardInfo.getValidityTime();
                                final String addr = idCardInfo.getAddress();
                                final String passNo = idCardInfo.getPassNum();
                                final int visaTimes = idCardInfo.getVisaTimes();
                                Bitmap bmpPhoto = null;
                                String imgStr = "";
                                if (idCardInfo.getPhotolength() > 0) {
//                                    idCardInfo.getPhoto()
                                    imgStr = decodeImg(idCardInfo.getPhoto());
                                }

                                try{
                                    idCardResult.put("resultCode",6);
                                    //照片
                                    idCardResult.put("photo",imgStr.replaceAll("\\n",""));
                                    //户籍地
                                    idCardResult.put("address",addr);
                                    //生日
                                    idCardResult.put("born",born);
                                    //发证机关
                                    idCardResult.put("grantDept",depart);
                                    //身份证号
                                    idCardResult.put("iDCardNo",licid);
                                    //名称
                                    idCardResult.put("name",name);
                                    //民族
                                    idCardResult.put("nation",nation);
                                    //性别
                                    idCardResult.put("sex",sex);
                                    //有效期结束
                                    idCardResult.put("userLifeEnd",expireDate);
                                }catch (JSONException e){
                                    throw new RuntimeException(e);
                                }
                            }
                            else
                            {
                                IDPRPCardInfo idprpCardInfo = idCardReader.getLastPRPIDCardInfo();
                                final String cnName = idprpCardInfo.getCnName();
                                final String enName = idprpCardInfo.getEnName();
                                final String sex = idprpCardInfo.getSex();
                                final String country = idprpCardInfo.getCountry() + "/" + idprpCardInfo.getCountryCode();//国家/国家地区代码
                                final String born = idprpCardInfo.getBirth();
                                final String licid = idprpCardInfo.getId();
                                final String expireDate = idprpCardInfo.getValidityTime();
                                final String depart = "公安部";
                                Bitmap bmpPhoto = null;
                                if (idprpCardInfo.getPhotolength() > 0) {
                                    decodeImg(idprpCardInfo.getPhoto());
                                }
//                                final int final_cardType = cardType;
//                                final Bitmap final_bmpPhoto = bmpPhoto;
//                                runOnUiThread(new Runnable() {
//                                    public void run() {
//                                        imgPhoto.setImageBitmap(final_bmpPhoto);
//                                        setResult("读卡成功，通讯耗时(ms)：" + nTickCommuUsed);
//                                        textNameContent.setText(cnName);
//                                        textENNameContent.setText(enName);
//                                        textSexContent.setText(sex);
//                                        textNationContent.setText(country);
//                                        textBornContent.setText(born);
//                                        textLicIDContent.setText(licid);
//                                        textDepartContent.setText(depart);
//                                        textExpireDateContent.setText(expireDate);
//                                    }
//                                });
                            }
                        }
                    }
                    countDownLatch.countDown();
                }
            }).start();
            bStarted = true;
            setResult(2,0,"打开设备成功，SAMID:" + idCardReader.getSAMID(0),null);
        } catch (IDCardReaderException e) {
//            e.printStackTrace();
            setResult(-3,-3,"打开设备失败"+e.getMessage(),null);
        }

    }

    public static Bitmap Bgr2Bitmap565(byte[] bgrbuf)
    {
        int width = com.zkteco.android.IDReader.WLTService.imgWidth;
        int height = com.zkteco.android.IDReader.WLTService.imgHeight;
        Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        int row = 0, col = width-1;
        for (int i = bgrbuf.length-1; i >= 3; i -= 3) {
            int color = bgrbuf[i] & 0xFF;
            color += (bgrbuf[i-1] << 8) & 0xFF00;
            color += ((bgrbuf[i-2]) << 16) & 0xFF0000;
            bmp.setPixel(col--, row, color);
            if (col < 0) {
                col = width-1;
                row++;
            }
        }
        return bmp;
    }

    // 推荐使用ARGB_8888
    public static Bitmap Bgr2Bitmap(byte[] bgrbuf)
    {
        int width = com.zkteco.android.IDReader.WLTService.imgWidth;
        int height = com.zkteco.android.IDReader.WLTService.imgHeight;
        Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        int row = 0, col = width-1;
        for (int i = bgrbuf.length-1; i >= 3; i -= 3) {
            int color = bgrbuf[i] & 0xFF;
            color += (bgrbuf[i-1] << 8) & 0xFF00;
            color += ((bgrbuf[i-2]) << 16) & 0xFF0000;
            color += 0xFF000000;
            bmp.setPixel(col--, row, color);
            if (col < 0) {
                col = width-1;
                row++;
            }
        }
        return bmp;
    }
}
